package id.mankel.commons.license;

import id.mankel.commons.constants.Asciis;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * mvn project-info-reports:dependencies
 * <p>target/site/dependencies.html</p>
 */
@Slf4j
public class JarLicenseCollector {

    public static void main(String[] args) throws IOException {
        collectFromMavenReport("D:\\workspace\\bosch_after_sales_service_dev\\target\\site\\dependencies.html");
    }

    static void collectFromMavenReport(String htmlPath) throws IOException {
        Document doc = Jsoup.parse(new File(htmlPath), StandardCharsets.UTF_8.name());
        String[] cssSelectors = {
                "[name=Project_Dependencies_compile] + section tr",
                "[name=Project_Transitive_Dependencies_compile] + section tr",
                "[name=Project_Transitive_Dependencies_runtime] + section tr",
        };
        // along with main package
        doCollect(doc, cssSelectors);
        // provided
        System.out.println("==================================================");
        doCollect(doc, "[name=Project_Dependencies_provided] + section tr");
    }

    private static void doCollect(Document doc, String... cssSelectors) {
        Stream.of(cssSelectors)
                .map(cssQuery -> {
                    Elements elements = doc.select(cssQuery);
                    return elements.parallelStream().map(e -> {
                        Elements tds = e.select("td");
                        Elements groupId = tds.eq(0);
                        Elements artifactId = tds.eq(1);
                        Elements version = tds.eq(2);
                        Elements license = tds.eq(4);
                        if (0 == license.size()) {
                            return null;
                        }
                        Elements as = license.select("a");
                        String licenses = as.stream().map(Element::text).collect(Collectors.joining(Asciis.SEMICOLON.s));
                        if (StringUtils.isBlank(licenses)) {
                            licenses = license.text();
                        }
                        String licenseUrls = as.stream().map(a -> a.attr("href")).collect(Collectors.joining(Asciis.SEMICOLON.s));
                        if (licenses.toUpperCase().contains("APACHE")) {
                            licenses = "Apache License 2.0";
                            licenseUrls = "http://www.apache.org/licenses/LICENSE-2.0.txt";
                        }
                        return new JarLicense(groupId.text(), artifactId.text(), version.text(), licenses, licenseUrls);
                    }).collect(Collectors.toList());
                })
                .collect(ArrayList<JarLicense>::new, List::addAll, List::addAll)
                .stream()
                .filter(Objects::nonNull)
                .sorted(Comparator.comparing(JarLicense::artifactId))
                .forEach(jl -> {
                    String s = new StringJoiner(Asciis.TAB.s)
                            .add(jl.groupId())
                            .add(jl.artifactId())
                            .add(jl.version())
                            .add(jl.license())
                            .add(jl.licenseUrl())
                            .toString();
                    System.out.println(s);
                });
    }

}
